import { Inject, Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '../../../common/base.service';
import { OrderManageEntity } from '../entity/orderManage';
import { getDateTimeDiff } from '../../../utils';
import { RoomUseRecordsService } from '../../roomUseRecords/service/roomUseRecords';
import { getDateFromUTC8 } from '../../../utils/date';
import { OrderManageDTO } from '../dto/orderManage';
import { RoomManageService } from '../../roomManage/service/roomManage';
import { BaseError as R } from '../../../common/base.error'

@Provide()
export class OrderManageService extends BaseService<OrderManageEntity> {

  @Inject()
  roomManageService: RoomManageService

  @Inject()
  roomUseRecordsService: RoomUseRecordsService;

  @InjectEntityModel(OrderManageEntity)
  orderManageModel: Repository<OrderManageEntity>;

  getModel(): Repository<OrderManageEntity> {
    return this.orderManageModel;
  }

  /** 签到 */
  async orderedSign(order: OrderManageEntity) {
    order.remaining_time = getDateTimeDiff(new Date(), order.order_end_date);
    this.roomUseRecordsService.create({
      roomId: order.room_id,
      roomName: order.room,
      roomType: order.type,
      startTime: order.order_date,
      startChargeTime: order.order_date,
      endTime: order.order_end_date,
      endChargeTime: order.order_end_date,
      useTime: order.remaining_time,
      isOut: false,
      outTime: '0'
    });
    order.start_charge_date = new Date();
    order.end_charge_date = order.order_end_date;
    return await this.edit(order);
  }


  /** 获取预约详情 */
  async getDetailById(id?: string) {
    try {

      const ordered = await this.getById(id);
      const purchaseDuration = getDateTimeDiff(ordered.order_date, ordered.order_end_date);
      const currentDate = getDateFromUTC8(new Date());
      const isOut = ordered.end_charge_date < currentDate;

      let outOfDate = '0';
      // 计算超时时长
      if (isOut) {
        outOfDate = getDateTimeDiff(currentDate, ordered.end_charge_date); 
      }
      
      return {
        ...ordered,
        isOut,
        outOfDate,
        purchaseDuration,
      }
    } catch (err) {
      console.error(err);
      throw err
    }
  }

  async createOrdered(ordered: OrderManageDTO) {
    try {
      const room = await this.roomManageService.getById(ordered.roomId);
      console.log('room: ', room);
      if (!room) {
        throw R.validateError('房间不存在!')
      }

      ordered.rooms = room;

      return await this.create(ordered.toEntity());

    } catch(err) {
      throw err
    }
  }
}